package model

import (
	"run_order/utils"

	"gorm.io/gorm"
)

type UserBasic struct {
	gorm.Model
	UserName string `json:"userName"`
	Password string `json:"password"`
	Phone    string `validate:"required,len=11" json:"phone"`
	Email    string `validate:"email" json:"email"`
	Name     string `json:"name"`
	Avatar   string `json:"avatar"`
	Salt     string `json:"salt"`
	// AddressList []Address `json:"addressList" gorm:"foreignKey:UserBasicId"` //重写外键，如果外键名刚好就叫UserBasicId也可以不用写
}

func (table *UserBasic) TableName() string {
	return "user_basic"
}

func GetUserList() []*UserBasic {
	userList := []*UserBasic{}
	// utils.DB.Preload("AddressList").Find(&userList)
	utils.DB.Find(&userList)
	return userList
}

func GetUserListPage(name string, userName string, page int, pageSize int) ([]*UserBasic, int64) {
	var total int64
	userList := []*UserBasic{}
	// utils.DB.Preload("AddressList").Find(&userList)
	utils.DB.Model(&userList).Where("name like ? and user_name like ?", "%"+name+"%", "%"+userName+"%").Count(&total).Offset(page - 1).Limit(pageSize).Find(&userList)
	// utils.DB.Find(&userList)

	return userList, total
}

func FindUserByOpenId(openId string) WxUser {
	user := WxUser{}
	utils.DB.Where("open_id = ?", openId).Find(&user)
	return user
}

// 新增
func CreateUser(user UserBasic) *gorm.DB {
	return utils.DB.Create(&user)
}

// 删除
func DeleteUserByID(user UserBasic) *gorm.DB {
	return utils.DB.Delete(&user)
}

// 修改
func UpdateUser(user UserBasic) *gorm.DB {
	// utils.DB.Find(&user)
	//调用save方法确认保存
	return utils.DB.Save(&user)
}

func FindUserByName(name string) UserBasic {
	user := UserBasic{}
	utils.DB.Where("user_name = ?", name).First(&user)
	return user
}
func FindUserByPhone(phone string) UserBasic {
	user := UserBasic{}
	utils.DB.Where("phone = ?", phone).First(&user)
	return user

}
func FindUserByEmail(email string) UserBasic {
	user := UserBasic{}
	utils.DB.Where("email = ?", email).First(&user)
	return user
}
